<template>
    <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
        <el-form class="tl-form" ref="dealform" :model="model" :rules="rules" label-width="120px">
            <el-row>
                <el-col :span="24">
                    <el-alert title="对于正常任务（非补录），实际开始日期只能选择今天或今天之后的日期，该日期代表任务相关人员的工作日志自动生成的开始日期！" show-icon type="warning" :closable="false">
                    </el-alert>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="实际开始日期" prop="actualstarttime" :rules="rules.validateRequire">
                        <el-date-picker v-model="model.actualstarttime" type="date" placeholder="实际开始日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="18">
                    <el-form-item label="任务取消原因" prop="cancelreason" v-if="showCancelTaskButton">
                        <el-input v-model="model.cancelreason" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5" :offset="1" style="padding-top:10px;">
                    <el-button type="danger" @click="doCancelTask" :loading="cancelLoading" v-if="showCancelTaskButton" :disabled="disableCancelTaskButton">任务取消</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-row>
            <el-col :span="24">
                <el-divider content-position="center"><span>【以下信息为只读信息】</span></el-divider>
            </el-col>
        </el-row>
        <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="120px" :disabled="disableEditSubmit || disableSave">
            <el-row style="margin-top:0px">
                <el-col :span="24">
                    <el-divider content-position="left"><span>1、【任务】相关信息</span></el-divider>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="里程碑" prop="milepostid" :required="true" :rules="rules.validateRequire">
                        <el-input v-model="model.dispmilepostid" :disabled="true" class="tl-ref-selector">
                            <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmMilepostRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="任务名称" prop="name" :rules="rules.validateRequire">
                        <el-input v-model="model.name"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="任务类型" prop="tasktype" :rules="rules.validateRequire">
                        <el-select v-model="model.tasktype" filterable clearable>
                            <el-option v-for="item in codeModel.tasktypeList" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="优先级" prop="priority" :rules="rules.validateRequire">
                        <el-select v-model="model.priority" filterable clearable>
                            <el-option v-for="item in codeModel.priorityList" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="任务类别" prop="taskcategory" :rules="rules.validateRequire">
                        <el-select v-model="model.taskcategory" filterable clearable @change="currentTaskState">
                            <el-option v-for="item in codeModel.taskcategoryList" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="任务状态" prop="taskstate">
                        <el-select v-model="model.taskstate" filterable clearable disabled>
                            <el-option v-for="item in codeModel.taskstateList" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="负责人" prop="leadername" :required="true" :rules="rules.validateRequire">
                        <el-input v-model="model.leadername" :disabled="true" class="tl-ref-selector">
                            <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmTeamRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="负责人工号" prop="leadercode">
                        <el-input v-model="model.leadercode" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="参与人" prop="participantnames">
                        <el-input v-model="model.participantnames" :disabled="true" class="tl-ref-selector">
                            <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmTeamParticipantRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="参与人工号" prop="participantcodes">
                        <el-input v-model="model.participantcodes" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="任务说明" prop="explain" :rules="rules.validateRequire">
                        <el-input v-model="model.explain" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="计划开始日期" prop="starttime" :rules="rules.validateRequire">
                        <el-date-picker v-model="model.starttime" type="date" placeholder="计划开始日期" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="计划结束日期" prop="endtime" :rules="rules.validateRequire">
                        <el-date-picker v-model="model.endtime" type="date" placeholder="计划结束日期" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <!-- <el-col :span="12" v-show="model.taskstate == '3' || model.taskstate == '4' ">
                    <el-form-item label="实际开始日期" prop="actualstarttime">
                        <el-date-picker v-model="model.actualstarttime" type="date" placeholder="实际开始日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                    </el-form-item>
                </el-col> -->
                <el-col :span="12" v-show="model.taskstate == '4'">
                    <el-form-item label="实际结束日期" prop="actualendtime">
                        <el-date-picker v-model="model.actualendtime" type="date" placeholder="实际完成日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-show="model.taskstate == '0'">
                    <el-form-item label="任务取消日期" prop="canceltime">
                        <el-date-picker v-model="model.canceltime" type="date" placeholder="任务取消日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="自评进度" prop="progress">
                        <el-input-number v-model="model.progress" controls-position="right" :step="10" :min="0" :max="100" style="width:95%" :disabled="true"></el-input-number>
                        <span>%</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="进度说明" prop="progressexplain">
                        <el-input v-model="model.progressexplain" type="textarea" :rows="2" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="备注" prop="description">
                        <el-input v-model="model.description" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-divider content-position="left"><span>2、【单据】相关信息</span></el-divider>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="派工部门" prop="deptname">
                        <tl-ref-dept v-model="model.deptcode" :initDisplayData.sync="model.deptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="派工公司" prop="orgname">
                        <el-input v-model="model.orgname" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="派工人" prop="username">
                        <tl-ref-user v-model="model.username" :initDisplayData.sync="model.username" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="派工人工号" prop="usercode">
                        <el-input v-model="model.usercode" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="单据日期" prop="docdate" :rules="rules.validateRequire">
                        <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="提交时间" prop="submitdate">
                        <el-date-picker v-model="model.submitdate" type="datetime" placeholder="提交时间" disabled></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="审批流程" prop="flowid">
                        <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="状态" prop="state">
                        <el-input v-model="model.dispstate" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <tl-approval-history ref="history" sourceType="PmTask" :sourceId="model.id" />
        <div slot="footer" class="dialog-footer">
            <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit" v-if="uiOperateState<=2">取消</el-button>
            <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave">
                <svg-icon icon-class="save" />保存</el-button>
            <!-- <el-button type="primary" @click="doCancelTask" :loading="cancelLoading" v-if="showCancelTaskButton" :disabled="disableCancelTaskButton">
                <svg-icon icon-class="undo" />任务取消</el-button> -->
            <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
                <svg-icon icon-class="send" />提交审批</el-button>
            <tl-attachment sourceType="PmTask" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit"></tl-attachment>
            <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
                <svg-icon icon-class="list" />审批历史</el-button>
            <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval">
                <svg-icon icon-class="undo" />取消审批</el-button>
        </div>
        <tlpm-milepost-ref ref="pmMilepostRef" @confirm="getpmMilepostRefData" :isSingleSelect="true"></tlpm-milepost-ref>
        <tlpm-team-ref ref="pmTeamRef" @confirm="getpmTeamRefData" :isSingleSelect="true" :externalQueryParam="{qry_projectid:model.projectid}"></tlpm-team-ref>
        <tlpm-team-ref ref="pmTeamParticipantRef" @confirm="getpmTeamParticipantRefData" :isSingleSelect="false" :externalQueryParam="{qry_projectid:model.projectid}"></tlpm-team-ref>
    </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlpmMilepostRef from '@/views/ProjectManage/pmMilepost/refList.vue'
import tlpmTeamRef from '@/views/ProjectManage/pmTeam/refList.vue'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
    mixins: [mixin_approval_edit],
    components: { tlpmMilepostRef, tlpmTeamRef },
    data() {
        return {
            moduleTitle: '任务管理',
            urlPrefix: '/pm/task/',
            url: {
                // 额外的url
                queryOrgByDeptId: "/pm/customer/queryOrgByDeptId",
                cancelTaskById: "/pm/task/cancelTask"
            },
            cancelLoading: false,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            }
        }
    },
    computed: {
        // 状态为已发布的任务才可以取消
        showCancelTaskButton() {
            return this.model.taskstate === '2'
        },
        // 只有任务负责人才可以使用此按钮
        disableCancelTaskButton() {
            return !(this.model.leadercode === this.user.code && this.model.taskstate === '2')
        }
    },
    methods: {
        assignDefaultValue() {
            if (this.isAdd) {
                if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
                    this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
                }
                this.$set(this.model, 'orgcode', this.org.code)
                this.$set(this.model, 'orgname', this.org.name)
                this.$set(this.model, 'deptcode', this.dept.code)
                this.$set(this.model, 'deptname', this.dept.fullname)
                this.$set(this.model, 'usercode', this.user.code)
                this.$set(this.model, 'username', this.user.name)
                this.$set(this.model, 'docdate', new Date())
                this.$set(this.model, 'progress', 0)
                // 开立1，已发布2，进行中3，完成4，取消0。
                // if (this.codeModel.taskstateList && this.codeModel.taskstateList.length > 0) {
                this.$set(this.model, 'taskstate', "1")
            }
        },
        loaded() {
            // 页面加载完毕执行
            if (!this.isAdd && this.model.docno) {
                this.title = this.title + `（单据编号：${this.model.docno}）`
            }
            // 避免管理员取消审批的单子，用户直接提交审批后实际开始时间出现误差
            this.$set(this.model, 'actualstarttime', '')
        },
        // 取消任务
        doCancelTask() {
            if (!this.model.cancelreason) {
                this.$tap.alert('请填写任务取消原因！')
                // this.$message({
                //     message: '请填写任务取消原因！',
                //     type: 'warning'
                // })
                return false
            }
            this.cancelLoading = true
            this.$tap.confirm('确定取消任务吗？')
                .then((_) => {
                    const param = {
                        taskId: this.model.id,
                        cancelReason: this.model.cancelreason
                    }
                    putAction(this.url.cancelTaskById, param)
                        .then((res) => {
                            if (res.success) {
                                this.$tap.message(res.message, 'success')
                                // 自动办理通过
                                this.$parent.$parent.$set(this.$parent.$parent, 'approvalopinion', "任务取消")
                                this.$parent.$parent.doApproval(1)
                            } else {
                                this.$tap.message(res.message, 'warning')
                            }
                            this.cancelLoading = false
                            this.queryData(this.model.id)
                        })
                })
                .catch((_) => {
                    this.cancelLoading = false
                })
        },
        currentTaskState() {
            if (this.model.taskcategory === '1') {
                this.$set(this.model, 'taskstate', '1')
                this.$set(this.model, 'progress', '0')
                this.$set(this.model, 'progressexplain', '')
                this.$set(this.model, 'actualstarttime', '')
                this.$set(this.model, 'actualendtime', '')
            }
            if (this.model.taskcategory === '2') {
                this.$set(this.model, 'taskstate', '4')
                this.$set(this.model, 'starttime', '')
                this.$set(this.model, 'endtime', '')
            }
        },
        onSelectDept(selectedDepts) {
            const selectedDept = selectedDepts[0]
            const { id, code, fullname } = selectedDept
            this.$set(this.model, "deptcode", code)
            this.$set(this.model, "deptname", fullname)
            const param = {
                deptId: id
            }
            getAction(this.url.queryOrgByDeptId, param).then((res) => {
                if (res.success) {
                    const { code: orgcode, name: orgname } = res.result
                    this.$set(this.model, "orgcode", orgcode)
                    this.$set(this.model, "orgname", orgname)
                } else {
                    this.$tap.alert("已选部门关联公司信息错误，请联系系统管理员")
                }
            })
        },
        /** 打开里程碑参照 */
        openpmMilepostRefDialog() {
            this.$refs.pmMilepostRef.visible = true
        },
        /** 获取里程碑参数数据 */
        getpmMilepostRefData(selectionRow, selectKey, selectionValue) {
            this.$set(this.model, 'milepostid', selectionRow.id)
            this.$set(this.model, 'dispmilepostid', selectionRow.milepostname)
            this.$set(this.model, 'projectid', selectionRow.projectid)
        },
        /** 打开负责人姓名参照 */
        openpmTeamRefDialog() {
            if (!this.model.milepostid) {
                this.$message({
                    message: '请先选择里程碑！',
                    type: 'warning'
                })
                this.$refs.pmTeamRef.visible = false
            } else {
                this.$refs.pmTeamRef.visible = true
            }
        },
        /** 获取负责人姓名参数数据 */
        getpmTeamRefData(selectionRow, selectKey, selectionValue) {
            debugger
            this.$set(this.model, 'leadername', selectionRow.username)
            this.$set(this.model, 'leadercode', selectionRow.usercode)
        },
        /** 打开参与人姓名参照 */
        openpmTeamParticipantRefDialog() {
            if (!this.model.milepostid) {
                this.$message({
                    message: '请先选择里程碑！',
                    type: 'warning'
                })
                this.$refs.pmTeamParticipantRef.visible = false
            } else {
                this.$refs.pmTeamParticipantRef.visible = true
            }
        },
        /** 获取参与人姓名参数数据 */
        getpmTeamParticipantRefData(selectedRows, selectedKeys, selectedValues) {
            let participantnames = ''
            let participantcodes = ''
            for (let { username, usercode } of selectedRows) {
                participantnames = participantnames + username + ","
                participantcodes = participantcodes + usercode + ","
            }
            if (participantnames.length > 0) {
                participantnames = participantnames.substring(0, participantnames.length - 1)
                participantcodes = participantcodes.substring(0, participantcodes.length - 1)
            }
            this.$set(this.model, 'participantnames', participantnames)
            this.$set(this.model, 'participantcodes', participantcodes)
        },
        saveActualStartTimeInfo(resolve, reject) {
            const { id, actualstarttime } = this.model
            if (!actualstarttime) {
                this.$tap.alert('请填写任务实际开始日期！')
                reject()
            }
            const param = {
                id,
                actualstarttime
            }
            putAction(this.url.edit, param)
                .then(res => {
                    if (res.success) {
                        resolve()
                    } else {
                        this.$tap.alert(res.message, 'warning')
                        reject()
                    }
                })
                .catch(err => {
                    this.$tap.alert('保存任务实际开始日期失败，请联系系统管理员', 'warning')
                    reject()
                })
        }
    }
}
</script>

